import { def } from './utils'

const arrPrt = Array.prototype
export const arrayMethods = Object.create(arrPrt)
const methodsToPatch = ['push', 'pop', 'shift', 'unshift', 'sort', 'reverse', 'splice']
methodsToPatch.forEach((item) => {
  const original = arrPrt[item]
  def(
    arrayMethods,
    item,
    function (...args) {
      const result = original.apply(this, args)
      const ob = this.__ob__
      let inserted
      switch (item) {
        case 'push':
        case 'unshift':
          inserted = args
          break
        case 'splice':
          inserted = args.slice(2)
      }
      // 如果要进行添加，对添加的内容重新observeArray
      if (inserted) ob.observeArray(inserted)
      ob.dep.notify()
      return result
    },
    false
  )
})
